package com.wasion.pwportable.jsi;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.wasion.core.config.Config;
import com.wasion.core.db.storage.SqliteStorage;
import com.wasion.core.db.storage.SqliteStorageListener.DataInsertListener;
import com.wasion.core.db.storage.SqliteStorageListener.DataQueryListener;
import com.wasion.core.db.storage.StorageQuery;
import com.wasion.core.db.storage.StorageQuery.SortOrder;
import com.wasion.core.util.DateTimeUtil;
import com.wasion.core.util.StringUtil;
import com.wasion.pwportable.activity.PwPortableActivity;
import com.wasion.pwportable.dao.sd.IndicatorSDDBDao;
import com.wasion.pwportable.dao.sd.LoadCurrentSDDBDao;
import com.wasion.pwportable.domain.po.Indicator;
import com.wasion.pwportable.domain.po.LoadCurrent;

/**
 * 
 * @ClassName: LoadCurrentJSI
 * @Description: 线路负载电流JavaScriptInterface<br/>
 *               1. 添加线路负荷电流 <br/>
 *               2. 展现三相负荷电流曲线 <br/>
 * @author 高意
 * @date 2014-8-1 下午2:57:06
 * 
 */
public class LoadCurrentJSI {

	// 应用上下文
	private Context context;

	// webview，浏览器窗口
	private WebView webView;

	// Sqlite存储实例
	private SqliteStorage sqliteStorage = null;

	// Google的Json转换工具
	private Gson gson = new Gson();

	// Excel sheet
	private WritableSheet sheet;

	private WritableWorkbook workBook;

	// 线路负荷电流数据库访问接口
	private LoadCurrentSDDBDao loadCurrentSDDBDao = null;

	// 主进程handler
	private Handler handler;

	// highcharts的data集合（每个元素为时间，值的数组）
	List<Object[]> dataList = new ArrayList<Object[]>();

	public LoadCurrentJSI(Context context) {
		this.context = context;
		this.webView = PwPortableActivity.getWebView();
		this.sqliteStorage = SqliteStorage.getInstance(this.context);
		this.loadCurrentSDDBDao = new LoadCurrentSDDBDao(context);
		this.handler = PwPortableActivity.getHandler();
	}

	/**
	 * 
	 * @Title: addLoadCurrent
	 * @Description: 新增线路负荷电流
	 * @param
	 * @return
	 * @throws
	 */
	public void addLoadCurrent(final String currentData,
			final String indicatorId) {

		handler.post(new Runnable() {
			public void run() {

				dataList = new ArrayList<Object[]>();

				String nowTime = DateTimeUtil
						.getCurrentDate("yyyy-MM-dd HH:mm");
				String[] timeArr = nowTime.split(":");
				String offMin = Integer.toString(5 * (Integer
						.parseInt(timeArr[1]) / 5));

				String[] data = currentData.split(",");

				String dataBeginTime = timeArr[0] + ":"
						+ (offMin.length() == 1 ? "0" + offMin : offMin)
						+ ":00";
				dataBeginTime = DateTimeUtil.getStringByOffset(dataBeginTime,
						"yyyy-MM-dd HH:mm:ss", Calendar.MINUTE, -1 * 5
								* (data.length - 1));

				Log.e(Config.LOG_TAG_GLOBOL, DateTimeUtil.getCurrentDate());
				List<LoadCurrent> currents = new ArrayList<LoadCurrent>();
				Date date2 = DateTimeUtil.StringToDate("1970-01-01",
						"yyyy-MM-dd");
				for (int i = data.length - 1; i >= 0; i--) {

					Date date = DateTimeUtil.StringToDate(dataBeginTime,
							"yyyy-MM-dd HH:mm:ss");

					LoadCurrent entity = new LoadCurrent();
					entity.setIndicatorid(Integer.parseInt(indicatorId));
					entity.setCurrent(Double.parseDouble(data[i]));
					entity.setTime(dataBeginTime);
					entity.setItime(new Date().getTime());

					currents.add(entity);

					Object[] record = new Object[] {
							(date.getTime() - date2.getTime()),
							Double.parseDouble(data[i]) };
					dataList.add(record);

					dataBeginTime = DateTimeUtil.getStringByOffset(
							dataBeginTime, "yyyy-MM-dd HH:mm:ss",
							Calendar.MINUTE, 5);
				}

				sqliteStorage.insertData(currents, loadCurrentSDDBDao,
						new DataInsertListener() {

							public void onSuccess(long paramLong) {
								try {
									Log.e(Config.LOG_TAG_GLOBOL,
											DateTimeUtil.getCurrentDate());
									String jsonStr = gson.toJson(dataList);
									webView.loadUrl("javascript:addLoadCurrentCallback("
											+ jsonStr + ")");
								} catch (Exception e) {
									JSIHelper.showToast(context, e.getMessage());
								}
							}

							public void onFailure(int errorCode,
									String errorMessage) {
								JSIHelper.showToast(context, "系统发生异常!");
							}
						});
			}
		});
	}

	/**
	 * 
	 * @Title: exportLoadCurrents
	 * @Description: 导出线路负载电流
	 * @param
	 * @return
	 * @throws
	 */
	public void exportLoadCurrents(final String beginDate, final String endDate) {

		handler.post(new Runnable() {
			public void run() {
				// 1. 按相位排序指示器
				StorageQuery storageQuery = new StorageQuery();
				storageQuery.addSort("phase", SortOrder.ASC);

				IndicatorSDDBDao indicatorSDDBDao = new IndicatorSDDBDao(
						context);
				sqliteStorage.findData(storageQuery, indicatorSDDBDao,
						new DataQueryListener() {

							public void onFailure(int errorCode,
									String errorMessage) {
								JSIHelper.showToast(context, "导出线路电流数据失败!");
							}

							public void onSuccess(List<?> paramList) {

								Map<String, Map<String, String>> timePhaseCurrents = getLoadCurrentMap(
										paramList, beginDate, endDate);
								try {
									String path = "";
									String fileName = DateTimeUtil
											.getCurrentDate("yyyyMMddHHmmss")
											+ ".xls";

									File usbDirectory = new File(Export
											.getUDiskPath());
									if (usbDirectory.exists()
											&& usbDirectory.isDirectory()
											&& usbDirectory.canWrite()) {
										path = Export.getUDiskPath() + "/"
												+ "电流数据/";
									} else {
										path = Export.getSDPath() + "/"
												+ "电流数据/";
									}

									File directory = new File(path);
									if (!directory.exists()
											&& !directory.isDirectory()) {
										directory.mkdirs();
									}

									File file = new File(path + fileName);
									if (!file.exists()) {
										file.createNewFile();
									}

									// 创建一个可写入的工作薄(Workbook)对象
									workBook = Workbook.createWorkbook(file);

									if (workBook != null) {
										// 第一个参数是工作表的名称，第二个是工作表在工作薄中的位置
										sheet = workBook.createSheet("电流数据", 0);

										// 设置表名和表头的行高
										sheet.setRowView(0, 800);
										sheet.setRowView(1, 600);

										// 合并单元格，在指定单元格插入表名
										sheet.mergeCells(0, 0, 3, 0);
										sheet.addCell(new Label(0, 0, "电流数据表",
												Export.getTitleCellFormat()));

										// 设置列宽
										sheet.setColumnView(0, 25);
										// 在指定单元格插入表头
										sheet.addCell(new Label(0, 1, "时间",
												Export.getHeaderCellFormat()));

										for (int i = 0; i < 3; i++) {
											String temp = i == 0 ? "( A 相 )"
													: (i == 1 ? "( B 相 )"
															: "( C 相 )");
											for (int j = 0; j < paramList
													.size(); j++) {
												int phase = Integer
														.parseInt(((Indicator) paramList
																.get(j))
																.getPhase());
												if (i + 1 == phase) {
													temp = ((Indicator) paramList
															.get(j))
															.getIndicatoraddr()
															+ temp;
												}
											}

											sheet.setColumnView(i + 1, 18);
											sheet.addCell(new Label(
													i + 1,
													1,
													temp,
													Export.getHeaderCellFormat()));
										}

										int row = 2;
										for (Entry<String, Map<String, String>> entry : timePhaseCurrents
												.entrySet()) {

											String key = entry.getKey();
											Map<String, String> value = entry
													.getValue();

											sheet.addCell(new Label(0, row,
													key,
													Export.getBodyCellFormat()));
											for (Entry<String, String> e0 : value
													.entrySet()) {

												String key0 = e0.getKey();
												String value0 = e0.getValue();
												sheet.addCell(new Label(
														Integer.parseInt(key0),
														row,
														value0,
														Export.getBodyCellFormat()));
											}

											row++;
										}

										// 从内存中写入文件中
										workBook.write();
										workBook.close();

										JSIHelper.showToast(context,
												"电流数据导出成功!");
										Map<String, Object> map = new HashMap<String, Object>();
										map.put("success", true);
										map.put("file", path + fileName);
										String result = gson.toJson(map);
										webView.loadUrl("javascript:exportLoadCurrentsCallback("
												+ result + ")");
									}
								} catch (Exception e) {
									e.printStackTrace();
									JSIHelper.showToast(context, "导出电流数据发生异常!");
								}
							}
						});
			}
		});
	}

	/**
	 * 
	 * @Title: getLoadCurrentMap
	 * @Description: 获取线路负载电流map
	 * @param
	 * @return
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Map<String, String>> getLoadCurrentMap(
			List<?> paramList, final String beginDate, final String endDate) {

		Map<String, Map<String, String>> timePhaseCurrents = new TreeMap<String, Map<String, String>>();

		// 2. 根据指示器查询时间段内的线路负载电流
		loadCurrentSDDBDao.startReadableDatabase(false);

		for (Indicator indicator : (List<Indicator>) paramList) {

			int indicatorId = indicator.get_id();

			StorageQuery storageQuery = new StorageQuery();
			storageQuery.equals("_id", indicatorId);
			if (!StringUtil.isEmpty(beginDate)) {
				storageQuery.greaterThanEqualTo("datetime(time)", beginDate);
			}
			if (!StringUtil.isEmpty(endDate)) {
				storageQuery.lessThanEqualTo("datetime(time)", endDate);
			}
			storageQuery.addSort("time,itime", SortOrder.ASC);

			List<LoadCurrent> list = loadCurrentSDDBDao.queryList(
					new String[] { "_id,current,time" },
					storageQuery.getWhereClause(), storageQuery.getWhereArgs(),
					null, null, storageQuery.getOrderBy(), null);

			String lastDateTime = "";
			for (LoadCurrent lc : list) {

				String time = lc.getTime();
				if (lastDateTime.equals(time)) {
					continue;
				}
				lastDateTime = lc.getTime();

				Map<String, String> currentsList = new HashMap<String, String>();
				if (timePhaseCurrents.containsKey(time)) {
					currentsList = timePhaseCurrents.get(time);
				}
				currentsList.put(indicator.getPhase(),
						Double.toString(lc.getCurrent()));

				timePhaseCurrents.remove(time);
				timePhaseCurrents.put(time, currentsList);
			}
		}
		loadCurrentSDDBDao.closeDatabase(false);

		return timePhaseCurrents;
	}

	/**
	 * 
	 * @Title: showLoadCurrentCurve
	 * @Description: 获取线路负载电流曲线
	 * @param
	 * @return
	 * @throws
	 */
	public void showLoadCurrentCurve(final String beginDate,
			final String endDate) {
		handler.post(new Runnable() {
			public void run() {
				// 1. 按相位排序指示器
				StorageQuery storageQuery = new StorageQuery();
				storageQuery.addSort("phase", SortOrder.ASC);

				IndicatorSDDBDao indicatorSDDBDao = new IndicatorSDDBDao(
						context);
				sqliteStorage.findData(storageQuery, indicatorSDDBDao,
						new DataQueryListener() {

							public void onFailure(int errorCode,
									String errorMessage) {
								JSIHelper.showToast(context, "查看电流曲线失败!");
							}

							@SuppressWarnings("unchecked")
							public void onSuccess(List<?> paramList) {

								try {

									List<Map<String, Object>> series = new ArrayList<Map<String, Object>>();
									Date date2 = DateTimeUtil.StringToDate(
											"1970-01-01", "yyyy-MM-dd");

									// 2. 根据指示器查询时间段内的线路负载电流
									loadCurrentSDDBDao
											.startReadableDatabase(false);
									for (Indicator indicator : (List<Indicator>) paramList) {

										int indicatorId = indicator.get_id();

										StorageQuery storageQuery = new StorageQuery();
										storageQuery.equals("_id", indicatorId);
										if (!StringUtil.isEmpty(beginDate)) {
											storageQuery
													.greaterThanEqualTo(
															"datetime(time)",
															beginDate);
										}
										if (!StringUtil.isEmpty(endDate)) {
											storageQuery.lessThanEqualTo(
													"datetime(time)", endDate);
										}
										storageQuery.addSort("time,itime",
												SortOrder.ASC);

										List<LoadCurrent> list = loadCurrentSDDBDao
												.queryList(
														new String[] { "_id,current,time" },
														storageQuery
																.getWhereClause(),
														storageQuery
																.getWhereArgs(),
														null, null,
														storageQuery
																.getOrderBy(),
														null);

										String lastDateTime = "";
										List<Object> data = new ArrayList<Object>();
										for (LoadCurrent lc : list) {
											if (lastDateTime.equals(lc
													.getTime())) {
												continue;
											}
											lastDateTime = lc.getTime();

											Date date = DateTimeUtil.StringToDate(
													lc.getTime(),
													"yyyy-MM-dd HH:mm:ss");
											Object[] record = new Object[] {
													(date.getTime() - date2
															.getTime()),
													lc.getCurrent() };
											data.add(record);
										}

										Map<String, Object> map = new HashMap<String, Object>();
										map.put("name",
												indicator.getIndicatoraddr());
										map.put("tooltip",
												"{'valueDecimals' : '4'}");
										map.put("data", data);

										series.add(map);
									}
									loadCurrentSDDBDao.closeDatabase(false);

									Map<String, Object> resultMap = new HashMap<String, Object>();
									resultMap.put("success", true);
									resultMap.put("series", series);
									String jsonStr = gson.toJson(resultMap);

									webView.loadUrl("javascript:showLoadCurrentCurveCallback("
											+ jsonStr + ")");
								} catch (Exception e) {
									e.printStackTrace();
									JSIHelper.showToast(context, "查看电流曲线发生异常!");
								}
							}
						});
			}
		});
	}
}
